package com.fuyq.filter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HeaderHttpRequestFilter implements HttpRequestFilter {

    private final String format = "HH";

    @Override
    public void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
        //限制访问时间
        Date now = new Date();
        SimpleDateFormat format = new SimpleDateFormat(this.format);
        String nowDate = format.format(now);
        try {
            if (!isEffectiveDate(nowDate, "12", "22")) {
                throw new RuntimeException("当前时间不允许访问");
            }
        } catch (ParseException exception) {
            exception.printStackTrace();
        }
        HttpHeaders headers = fullRequest.headers();
        if (headers == null) {
            headers = new DefaultHttpHeaders();
        }
        headers.add("proxy-tag", this.getClass().getSimpleName());
    }

    private boolean isEffectiveDate(String nowDate, String startDate, String endDate) throws ParseException {
        Date startTime = new SimpleDateFormat(this.format).parse(startDate);
        Date endTime = new SimpleDateFormat(this.format).parse(endDate);
        Date nowTime = new SimpleDateFormat(this.format).parse(nowDate);

        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        long now = nowTime.getTime();
        long begin = startTime.getTime();
        long end = endTime.getTime();

        return now > begin && now < end;
    }
}
